class Solution {
public:
    string minWindow(string S, string T) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<int> count(256);
        vector<int> curCount(256);
        int n = S.length();
        int m = T.length();

        for (int i = 0; i < m; ++i) {
            count[T[i]]++;
        }

        int sum = 0;
        int start = -1;
        int end = -1;
        for (int i = 0, j = 0; i < n; ++i) {
            ++curCount[S[i]];
            if (curCount[S[i]] <= count[S[i]]) {
                ++sum;
            }
            while (curCount[S[j]] > count[S[j]]) {
                --curCount[S[j]];
                ++j;
            }
            if (sum == m) {
                if (start == -1) {
                    start = j;
                    end = i;
                } else if (end - start + 1 > i - j + 1) {
                    start = j;
                    end = i;
                }
            }
        }

        return start < 0 ? string("") : S.substr(start, end - start + 1);
    }
};
